// pages/jointMarketing/storesDetails/storesDetails.js
const app = getApp()
const WXAPI = require("../../../../api/api")
Page({
  /** 
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: ' ', // 导航栏 中间的标题
      textColor: '#333', // 标题颜色
      bgColor: '#F75D0B', // 导航栏背景颜色
      background: '',
      opacity:'',
    },

    loading: true,
    title: '还没有发布的积分哦',
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.systeminfo.statusBarHeight * 2 + 20,
    topHeight: '',
    scroll_height: '',//系统高度
    scroll_height_1: '',
    storeDetail: '',
    tabList:[
      {id: 0,text: "商家图片"},
      {id: 1,text: "证照信息"},
      {id: 2,text: "品牌介绍"},
      {id: 3,text: "营业时间"},
    ],
    currentNavtab:0,
    isblank: false, //列表是否为空
    shopId: '',
    storesData:{},
    imgHttp: app.globalData.imgHttp,
    lnt: app.globalData.lnt,//经度
    lat: app.globalData.lat,//维度
    shopBusiness:'',
    integralstatus:'',
    shopStatus:'',
    cardList:[],
    vouchers:[],//券列表
    assetType:2,//资产类型 1 积分 2 券
    pageNum:1,
    pageSize:3,
    ischeckLinkageTime: '',//是否可以通兑
    isActivity: false,//店内活动开启下拉
    integralMore: false,//是否开启剩余按钮
    moreNum: '',
    scrollY: false,
    cardIndex: 1,//当前第几张图片
    preferential_boxTop: '',
    information_boxTop: '',
    phoneShow: false,
    phoneList: [],
    levelTipShow:false,//商家等级说明弹窗
    levelInfo:{},//等级详情
    starnum: 5,
    evaluateTotal: 0,
    evaluateList:[],
    merchantId: '',
    bulkList: [],
    superviseTipShow: false,//资金监管弹窗
    superviseRatio: 0,//资金监管数额
    tipsShow: false,//签约保险说明弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)
    let scene = decodeURIComponent(options.scene)
    let url = decodeURIComponent(options.q)
    var shopId = ''
    if (url != '' && url != 'undefined') { //扫码进入
      let b = url.lastIndexOf("="); //截取等号后的内容
      shopId = url.substring(b + 1, url.length);
    }else if (scene != '' && scene != 'undefined') { //扫太阳码进入
      let sceneUrl = scene.lastIndexOf("="); //截取等号后的内容
      shopId = scene.substring(sceneUrl + 1, scene.length);
    }else { //其他情况进入
      shopId = options.shopId
    }
    this.setData({
      shopId: shopId,
    })
    this.isGetSetting()
    // this.merchantDetail()
    this.view_height()
    this.getqualificationImg()
    this.getLevelTips()
    
  },
  onShow() {
    this.login_dialog = this.selectComponent("#login_dialog");
  },
  getLevelTips() { //获取商家信用等级
    var shopId = this.data.shopId
    var url = `/app/v1/customer/shop/credit/${shopId}`
    WXAPI.levelTips(url, '', res => {
      this.setData({
        levelInfo: res.result
      })
    })
  },
    //更多资质
  goQualification(){
    var shopId = this.data.shopId
    wx.navigateTo({
      url: '/userPageB/pages/userStore/qualification/qualification?shopId='+shopId,
    })
  },
  //获取位置授权
  isGetSetting() {
    var that = this;
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
      var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //没授权
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              app.globalData.lat = res.latitude//维度
              app.globalData.lnt = res.longitude//经度
              that.setData({
                lat: res.latitude,//维度
                lnt: res.longitude,//经度
              })
              that.merchantDetail()
            },fail: function(res){
              that.merchantDetail()
            },
          })
        } else { 
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              app.globalData.lat = res.latitude//维度
              app.globalData.lnt = res.longitude//经度
              that.setData({
                lat: res.latitude,//维度
                lnt: res.longitude,//经度
              })
              that.merchantDetail()
            },fail: function(res){
              that.merchantDetail()
            },
          })
        }
      }
    })
  },
  //店铺卡列表
  shopcardList(){
    const that = this
    var data = {
      shopId: this.data.shopId,
      pageSize: 3,
      pageNum: 1,
    }
    WXAPI.shopcardList(data, (res) =>{
      const data = res.result
      const {records} = res.result
      if(res.code === 200){
        that.setData({
          cardList: records,
          total:res.result.total
        })
        console.log("that.data.cardList",that.data.cardList)
      }
    })
  },
  //获取商户信息
  merchantDetail(id){
    const that = this
    var data = {
      shopId: this.data.shopId,
      lnt: this.data.lnt,
      lat: this.data.lat,
    }
    WXAPI.userMerchantDetail(data, (res) =>{
      const data = res.result
      if(res.code === 200){
        if (data.type==1) { //只有是入驻商家才请求卡列表
          this.shopcardList()
        }
        var phone = data.phone
        this.data.phoneList = phone.split(',')
        that.setData({
          phoneList: this.data.phoneList,
          storesData:data,
          shopBusiness: data.shopBusiness,
          merchantId: data.merchantId,
        })
        this.getEvaluateList()
      }
    })
  },
  //展示图片
  showImg:function(e){
    var that = this;
    let imglists = that.data.storesData.shopImgList.map((item, index)=>{
      item = that.data.imgHttp+item
      return item
    })
    wx.previewImage({
        urls: imglists,
        current: that.data.imgHttp + that.data.storesData.shopImgList[e.currentTarget.dataset.index]
    })
  },
  //证件照
  showPicture:function(e){
    var that = this;
    let imglists = that.data.imgList.map((item, index)=>{
      item = that.data.imgHttp+item
      return item
    })
    wx.previewImage({
        urls: imglists,
        current: that.data.imgHttp + that.data.imgList[e.currentTarget.dataset.index]
    })
  },
  //评论照片
  showEvaluateImg: function (e) {//展示图片
    var that = this;
    let imglists = e.currentTarget.dataset.img
    imglists = imglists.map((item, index) => {
      return that.data.imgHttp + item
    })
    wx.previewImage({
      urls: imglists,
      current: imglists[e.currentTarget.dataset.index]
    })
  },

  handleTo(e){
    var id = e.currentTarget.dataset.id
    var data = {
      assetId:id,
    }
    WXAPI.checkLinkageTime( data, (res) =>{
      const data = res.result
      if(res.code === 200){
        wx.navigateTo({
          url: '/merchantsPageB/pages/jointMarketing/InitiateOr/InitiateOr?id='+id,
        })
      }else{
        wx.showToast({
          title: res.message,
          icon: none
        })
      }
    })
  },
  //店铺图片滑动监听
  handleChange(e){ 
    let index = e.detail.current
    this.setData({
      cardIndex: index + 1,
    })
   
  },
  //导航到地方
  getLocation:function(){
    const that = this

    wx.getSetting({
      success: (res) => {
      var statu = res.authSetting;
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
        wx.showModal({
          title: '',
          content: '需要获取你的地理位置才能进行导航，请确认授权',
          success: function (res) {
            if (res.cancel) {
              wx.showToast({
                title: '拒绝授权',
                icon: 'none'
              })
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    //再次授权，调用wx.getLocation的API
                    that.newgetLocation(dataAu, callback)
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          }
        })
      } else { 
          that.newgetLocation()
        }
      }
    }) 
  },
  handlePhoneShow(){
    this.setData({
      phoneShow: !this.data.phoneShow
    })
  },
  //拨打电话
  freeTell(e){
    var phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  newgetLocation(){
    const storesData = this.data.storesData
    wx.getLocation({
      type: 'gcj02', 
      success: function (res) {
        wx.openLocation({//​使用微信内置地图查看位置。
          latitude: storesData.shopLat,//要去的纬度-地址
          longitude: storesData.shopLnt,//要去的经度-地址
          name: storesData.merchantName,
          address: storesData.locateAddress
        })
      }
    })
  },
  handleactivity(){
    this.setData({
      isActivity: !this.data.isActivity
    })
  },
  

  tabClick(e){
    this.setData({
      currentNavtab: e.currentTarget.dataset.id,
    })
  },
  //信息公示
  hangdleInformation(){
    var shopId = this.data.shopId
    wx.navigateTo({
      url: '/userPageB/pages/userStore/qualificationImg/qualificationImg?shopId='+shopId,
    })
  },
  //证照信息
  getqualificationImg(){
    const that = this
    var shopId = this.data.shopId
    var url = `/app/v1/customer/shop/competencyImages/${shopId}`
    WXAPI.competencyImages(url, '' , (res) =>{
      const {result} = res
      if(res.code === 200){
        that.setData({
          imgList: result,
        })
      }
    })
  },
  //股东卡列表
  handleCardMore(){
    wx.navigateTo({
      url: '/userPageB/pages/userStore/theCards/theCards?shopId='+this.data.shopId,
    })
  },
  handleCard(e){
    var id = e.currentTarget.dataset.id
    var isSoldOut = e.currentTarget.dataset.is
    var merchantId = e.currentTarget.dataset.merchantid
    if(isSoldOut){
      wx.showModal({
        title: '此张储值卡已售完，试试其他可购买的储值卡',
        showCancel: false,
        confirmColor:'#FF5800',
        confirmText: '我已知晓',
        success (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/userPageB/pages/userStore/cardDetail/cardDetail?assetId='+id+'&merchantId='+merchantId,
    })
  },
  //逛逛其他店铺
  handleshop(){
    wx.redirectTo({
      url: '/userPageB/pages/userMarket/merchantsList/merchantsList?id='+'',
    })
  },
  lookLevleTip(){ //商家等级说明
    this.setData({
      levelTipShow: true
    })
  },
  view_height: function() {
    let that = this
    var height = wx.getSystemInfoSync().windowHeight
      that.setData({
        scroll_height: height+"px",
        scroll_height_1:  height - app.globalData.headerHeight+"px",
      })
  },
  onPageScroll (e) { 
    var that = this;
    var scrollY = e.scrollTop
    if(scrollY > 200){
      that.setData({
        scrollY: true,
        ['nvabarData.background']: '#fff',
        ['nvabarData.opacity']: '1',
        ['nvabarData.isColor']: true,
      })
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#000000',
      })
    }else if(scrollY > 50 && scrollY < 200){
      that.setData({
        ['nvabarData.background']: '#fff',
        ['nvabarData.opacity']: '0.4',
        ['nvabarData.title']: that.data.storesData.shopName,
      })
    }else if(scrollY < 50){
      that.setData({
        scrollY: false,
        ['nvabarData.background']: '',
        ['nvabarData.opacity']: '',
        ['nvabarData.title']: ' ',
        ['nvabarData.isColor']: false,
      })
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
      })
    }
  },
  //滚动监听
  scroll: function (e) {
    var that = this;
    var scrollY = e.detail.scrollTop
    if(scrollY > 300){
      that.setData({
        scrollY: true,
        ['nvabarData.background']: '#fff',
        ['nvabarData.opacity']: '1',
      })
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#000000',
      })
    }else if(scrollY > 50 && scrollY < 300){
      that.setData({
        ['nvabarData.background']: '#fff',
        ['nvabarData.opacity']: '0.4',
        ['nvabarData.title']: that.data.storesData.shopName,
      })
    }else if(scrollY < 50){
      that.setData({
        scrollY: false,
        ['nvabarData.background']: '',
        ['nvabarData.opacity']: '',
        ['nvabarData.title']: ' ',
      })
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
      })
    }
    
  },
  //评价列表
  getEvaluateList(){
    if (this.data.merchantId=='') {
      return
    }
    const data = {
      merchantId: this.data.merchantId,
      pageNum: 1,
      pageSize: 2,
    }
    WXAPI.getEvaluateList(data,(res) => {
      this.data.evaluateList = res.result.records.map(item => {
        if (item.image) {
          item.image = JSON.parse(item.image)
        }
        
        item.totalPoints = item.totalPoints / 2
        return item
      })
      this.setData({
        evaluateList: this.data.evaluateList,
        evaluateTotal: res.result.total
      })
    })
  },
   /* 去抢购 */
   handlePay(e){
    const id = e.currentTarget.dataset.id
    const token = wx.getStorageSync('token');
    if(token){
      wx.navigateTo({
        url: '/userPageC/pages/confirmOrder/confirmOrder?grouponId='+id,
      });
    }else{
      this.login_dialog.loginShow()
    }
  },
  /* 登陆成功 */
  loginSuccess(){
    
  },
  /* 获取店铺团购 */
  handleShopAbulk(e){
    const shopId = this.data.shopId
    const token = wx.getStorageSync('token');
    if(token){
      wx.navigateTo({
        url: '/userPageC/pages/shopBulk/shopBulk?shopId='+shopId,
      });
    }else{
      this.login_dialog.loginShow()
    }  
  },
  //更多评价
  handleEva(){
    wx.navigateTo({
      url: '/userPageB/pages/evaluationList/evaluationList?merchantId='+this.data.merchantId,
    })
  },
  //资金监管弹窗
  superviseTipView(e){
    let num = e.currentTarget.dataset.superviseratio
    this.setData({
      superviseTipShow: true,
      superviseRatio: num
    })
  },
  //签约保险说明弹窗
  signedView(){
    this.setData({
      tipShow: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    setTimeout(() => {
      this.setData({
        loading: false
      })
    }, 500);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh(){
    setTimeout(() => {
      wx.stopPullDownRefresh()
    },2000);
  },
   /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title:  "【"+this.data.storesData.shopName +"】"+ '快来试试这家店吧!',
    }
  },
})